
import sys
import json
import cgi
import georef
from osgeo import ogr
import time

def application(environ, start_response):

    form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ)
    gref = georef.georef.make_georef(form)
    bbox = gref.get_bounding_box()
    zoom = int(form["zoom"].value)
    conn = ogr.Open("PG: host=localhost dbname=counties user=counties password=bogus")
    args = tuple(map(str,[georef.reduction_tolerances[zoom]] + bbox))
    q = "select st_asbinary(st_simplify(the_geom_merc,%s)), countyname, state, time_zone, lat, lon from counties where st_transform(the_geom,4326) && setsrid('BOX(%s %s, %s %s)'::box2d,4326)" % args #really bad here, these inputs need to be cleaned, ExecuteSQL doesn't support prepared statements
    cur = conn.ExecuteSQL(q)
    recs = []
    for feature in cur:
        geom = feature.GetGeometryRef()
        county = feature.GetFieldAsString(0)
        state = feature.GetFieldAsString(1)
        tz = feature.GetFieldAsString(2)
        polys = gref.draw_polygon_from_geom(geom,(255,64,128,255))
        recs.append([polys,county,state,tz])
    conn.ReleaseResultSet(cur)
    output = gref.get_image()
    output = json.dumps({"img":gref.get_base64(),"recs":recs})
    response_headers = [('Content-type', 'text/html'),
                        ('Content-Length', str(len(output)))]
    start_response('200 OK', response_headers)
    return [output]
